from fastapi import APIRouter, FastAPI, Depends
from importlib import import_module
from typing import Any
from core.token_manager import get_current_user
from core.base.api_mode import api_success
from config.router_config import ROUTE_CONFIG

# 创建v1版本API路由器
api_v1_router = APIRouter()

def _load_router(router_path: str) -> Any:
    """根据配置中的 import 路径加载 router 对象。
    支持 "package.module:attribute"，未写 attribute 默认取 "router"。
    """
    if ":" in router_path:
        module_name, attr_name = router_path.split(":", 1)
    else:
        module_name, attr_name = router_path, "router"
    module = import_module(module_name)
    return getattr(module, attr_name)

# 按配置动态注册各模块路由到 v1 路由器
for cfg in ROUTE_CONFIG:
    router_obj = _load_router(cfg["import"])
    deps = [Depends(get_current_user)] if cfg.get("auth") else []
    api_v1_router.include_router(
        router_obj,
        prefix=cfg["prefix"],
        tags=cfg.get("tags", []),
        dependencies=deps,
    )



def register_routers(app: FastAPI):
    """注册所有路由"""
    
    # 根路由
    @app.get("/")
    async def root():
        return api_success({"message": "Welcome to Case App API"}, msg="服务正常")
    
    # API v1路由
    app.include_router(
        api_v1_router,
        prefix="/api/v1",
        tags=["v1"]
    )